<template>
	<view class="page-container">
		<!-- 顶部栏 -->
		<view class="top-bar">
			<!-- 广告轮播 -->
			<swiper 
				class="adv-swiper" 
				:indicator-dots="true" 
				:autoplay="true" 
				:interval="3000" 
				:duration="500"
				:circular="true"
				indicator-color="rgba(255, 255, 255, 0.5)"
				indicator-active-color="#667eea"
			>
				<swiper-item v-for="(adv, index) in advList" :key="index">
					<image 
						:src="adv.imageUrl" 
						class="adv-image" 
						mode="aspectFill"
						@error="onAdvImageError(adv)"
						@click="onAdvClick(adv)"
					></image>
				</swiper-item>
				<!-- 无广告时显示默认内容 -->
				<swiper-item v-if="advList.length === 0">
					<view class="adv-placeholder">
						<text class="placeholder-text">欢迎使用自动售卖机</text>
					</view>
				</swiper-item>
			</swiper>
			
			<!-- 搜索栏 -->
			<view class="search-bar">
				<view class="search-input-wrapper">
					<view class="search-icon">
						<image src="/static/soushou.png"/>
					</view>
					<input 
						v-model="searchKeyword" 
						class="search-input" 
						placeholder="搜索商品名称" 
						placeholder-class="search-placeholder"
						@input="onSearchInput"
					/>
					<text v-if="searchKeyword" class="clear-icon" @click="clearSearch">✕</text>
				</view>
			</view>
			
			<!-- 排序选项 -->
			<view class="sort-bar">
				<view 
					v-for="sort in sortOptions" 
					:key="sort.value"
					class="sort-item"
					:class="{ active: sortBy === sort.value }"
					@click="changeSortBy(sort.value)"
				>
					<text class="sort-text">{{ sort.label }}</text>
					<text v-if="sortBy === sort.value" class="sort-arrow">{{ sort.arrow }}</text>
				</view>
			</view>
		</view>
		
		<!-- 主内容区 - 左右布局 -->
		<view class="main-content">
			<!-- 左侧分类栏 -->
			<scroll-view class="category-sidebar" scroll-y="true" :show-scrollbar="false">
				<view class="category-title">📂 分类</view>
				<view 
					v-for="category in categories" 
					:key="category.value"
					class="category-item"
					:class="{ active: selectedCategory === category.value }"
					@click="selectCategory(category.value)"
				>
					<text class="category-icon">{{ category.icon }}</text>
					<text class="category-name">{{ category.label }}</text>
					<text v-if="category.count > 0" class="category-count">{{ category.count }}</text>
				</view>
			</scroll-view>
			<!-- 右侧商品列表 -->
			<scroll-view class="product-area" scroll-y="true" :show-scrollbar="false">
				<!-- 加载状态 -->
				<view v-if="loading" class="loading-container">
					<image src="../../static/loading.gif" class="loading-icon"></image>
					<text class="loading-text">加载中...</text>
				</view>
				
				<!-- 商品网格 -->
				<view v-else-if="loaded && filteredItems.length > 0" class="product-grid">
					<view 
						v-for="(item, index) in filteredItems" 
						:key="item.id"
						class="product-card"
						@click="onProductItemClicked(index)"
					>
						<!-- 收藏按钮 -->
						<view class="favorite-btn" @click.stop="toggleFavorite(item)">
							<text class="favorite-icon">{{ item.isFavorite ? '❤️' : '🤍' }}</text>
						</view>
						
						<!-- 商品图片 -->
						<image 
							:src="item.imageUrl" 
							@error="onImageError(item)" 
							class="product-image"
							mode="aspectFill"
						></image>
						
						<!-- 商品信息 -->
						<view class="product-info">
							<text class="product-name">{{ item.name }}</text>
							<view class="product-meta">
								<text class="product-price">¥{{ item.price }}</text>
								<text class="product-sales" v-if="item.sales > 0">销量{{ item.sales }}</text>
							</view>
							<view class="product-footer">
								<text class="product-stock" :class="{ 'low-stock': item.stock <= 5 }">
									{{ item.stock > 0 ? `库存${item.stock}` : '已售罄' }}
								</text>
								<button 
									class="buy-btn" 
									:class="{ disabled: item.stock <= 0 }"
									@click.stop="onProductItemClicked(index)"
									:disabled="item.stock <= 0"
									size="mini"
								>
									{{ item.stock > 0 ? '购买' : '售罄' }}
								</button>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view v-else-if="loaded && filteredItems.length === 0" class="empty-container">
					<text class="empty-icon">📦</text>
					<text class="empty-text">{{ searchKeyword || selectedCategory !== 'all' ? '没有找到相关商品' : '暂无商品' }}</text>
					<button class="empty-button" @click="resetFilters">重置筛选</button>
				</view>
				
				<!-- 错误状态 -->
				<view v-else class="error-container">
					<text class="error-icon">⚠️</text>
					<text class="error-text">加载失败</text>
					<button class="error-button" @click="fetchProductList">重试</button>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import Product from '../../models/product.js';
	let tag = "product-list";
	export default {
		onLoad() {
			// 页面初始化
		},

		data() {
			return {
				loading: false,
				loaded: false,
				default_path: "/static/error.png",
				items: [],  // 原始商品列表
				
				// 广告轮播
				advList: [],
				
				// 搜索和筛选
				searchKeyword: "",
				selectedCategory: "all",
				sortBy: "default",
				
				// 排序选项
				sortOptions: [
					{ label: "默认", value: "default", arrow: "" },
					{ label: "价格↑", value: "price_asc", arrow: "↑" },
					{ label: "价格↓", value: "price_desc", arrow: "↓" },
					{ label: "销量", value: "sales", arrow: "🔥" },
					{ label: "最新", value: "newest", arrow: "✨" }
				],
				
				// 分类选项（动态生成）
				categories: [
				    { label: "全部", value: "all", icon: "🏪", count: 0 }
				]
			}
		},
		
		computed: {
			// 过滤和排序后的商品列表
			filteredItems() {
				let result = [...this.items];
				
				// 1. 搜索过滤
				if (this.searchKeyword) {
					const keyword = this.searchKeyword.toLowerCase();
					result = result.filter(item => 
						item.name.toLowerCase().includes(keyword)
					);
				}
				
				// 2. 分类过滤
				if (this.selectedCategory !== 'all') {
					result = result.filter(item => item.category === this.selectedCategory);
				}
				
				// 3. 排序
				switch (this.sortBy) {
					case 'price_asc':
						result.sort((a, b) => a.price - b.price);
						break;
					case 'price_desc':
						result.sort((a, b) => b.price - a.price);
						break;
					case 'sales':
						result.sort((a, b) => b.sales - a.sales);
						break;
					case 'newest':
						result.sort((a, b) => {
							if (!a.createTime) return 1;
							if (!b.createTime) return -1;
							return new Date(b.createTime) - new Date(a.createTime);
						});
						break;
				}
				
				return result;
			}
		},

		onShow() {
			// 页面显示时重新获取商品列表，确保数据最新
			this.fetchProductList();
			// 获取广告列表
			this.fetchAdvList();
			// 更新收藏状态
			this.updateFavoriteStatus();
		},

		methods: {
			// 更新商品收藏状态
			updateFavoriteStatus() {
				this.items.forEach(item => {
					item.isFavorite = this.$favoriteManager.isFavorite(item.id);
				});
			},
			
			// 动态生成分类导航
			generateCategories() {
			    // 获取所有唯一的分类名称
			    const categoryNames = [...new Set(this.items.map(item => item.category))];
			    
			    // 分类图标映射
			    const iconMap = {
			        '水': '💧',
			        '瓶装饮料': '🍾',
			        '罐装饮料': '🥫',
			        '饮料': '🥤',
			        '零食': '🍿',
			        '日用品': '🧴',
			        '其他': '📦'
			    };
			    
			    // 重置分类列表，保留"全部"
			    this.categories = [
			        { label: "全部", value: "all", icon: "🏪", count: this.items.length }
			    ];
			    
			    // 添加动态分类
			    categoryNames.forEach(categoryName => {
			        const count = this.items.filter(item => item.category === categoryName).length;
			        if (count > 0) {
			            this.categories.push({
			                label: categoryName,
			                value: categoryName,
			                icon: iconMap[categoryName] || '📦',
			                count: count
			            });
			        }
			    });
			    
			    // 添加"其他"分类（空状态）
			    this.categories.push({
			        label: "其他",
			        value: "其他",
			        icon: "📦",
			        count: 0
			    });
			    
			    this.$log.info(tag, `动态生成 ${this.categories.length} 个分类`);
			},
			
			// 搜索输入
			onSearchInput() {
				this.$log.info(tag, `搜索: ${this.searchKeyword}`);
			},
			
			// 清除搜索
			clearSearch() {
				this.searchKeyword = "";
			},
			
			// 切换排序方式
			changeSortBy(value) {
				this.sortBy = value;
				this.$log.info(tag, `排序方式: ${value}`);
			},
			
			// 选择分类
			selectCategory(value) {
				this.selectedCategory = value;
				this.$log.info(tag, `选择分类: ${value}`);
			},
			
			// 重置所有筛选
			resetFilters() {
				this.searchKeyword = "";
				this.selectedCategory = "all";
				this.sortBy = "default";
			},
			
			// 切换收藏
			toggleFavorite(item) {
				const isFavorite = this.$favoriteManager.toggleFavorite(item.id);
				item.isFavorite = isFavorite;
				
				uni.showToast({
					icon: 'success',
					title: isFavorite ? '已收藏' : '已取消收藏',
					duration: 1000
				});
				
				this.$log.info(tag, `${isFavorite ? '收藏' : '取消收藏'}: ${item.name}`);
			},
			
			onImageError(item) {
				this.$log.info(tag, "图片加载失败，使用默认图片");
				item.imageUrl = this.default_path;
			},

			onProductItemClicked(index) {
				const product = this.filteredItems[index];

				// 检查库存
				if (product.stock <= 0) {
					uni.showToast({
						icon: 'none',
						title: '商品已售罄',
						duration: 1500
					});
					return;
				}

				// 如果已登录，跳转"购买商品页"
				if (this.$loginManager.isLoggedIn()) {
					this.$log.info(tag, "已登录，跳转到购买页面")
					try {
						let productJsonString = JSON.stringify(product);
						uni.navigateTo({
							url: `/pages/purchase/purchase?product=${encodeURIComponent(productJsonString)}`
						});
					} catch (e) {
						this.$log.error(tag, "跳转购买页面失败:", e);
						uni.showToast({
							icon: 'none',
							title: '跳转失败',
							duration: 1500
						});
					}
				} else {
					//如果未登录，跳转"登录页"
					this.$log.info(tag, "未登录，跳转到登录页面")
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}
			},

			fetchProductList() {
				this.$log.info(tag, "fetchProductList");
				this.loading = true;
				this.loaded = false;
				this.items = [];

				try {
					uni.request({
						url: `${this.$constant.BASE_URL}/api/machine/products`,
						method: 'GET',
						data: {
							'machineNo': this.$constant.MACHINE_NO,
						},
						header: {
							'content-type': 'application/x-www-form-urlencoded'
						},
						success: (res) => {
							this.$log.info(tag, ' 获取商品列表请求成功 - 响应数据:', res.data);
							this.loading = false;
							this.loaded = true;

							if (res && res.data) {
								if (res.data.code === 200) {
									try {
										this.items = this.parseProductList(res.data);
										this.updateFavoriteStatus();
										this.generateCategories();
										this.$log.info(tag, `成功解析 ${this.items.length} 个商品`);
									} catch (parseError) {
										this.$log.error(tag, "解析商品列表异常:", parseError);
										this.items = [];
										uni.showToast({
											icon: 'none',
											title: '解析商品数据失败',
											duration: 1500
										});
									}
								} else {
									this.$log.error(tag, "获取商品列表返回错误:", res.data);
									uni.showToast({
										icon: 'none',
										title: res.data.msg || '获取商品失败',
										duration: 1500
									});
								}
							} else {
								this.$log.error(tag, "获取商品列表返回无效数据");
								uni.showToast({
									icon: 'none',
									title: '服务器返回无效数据',
									duration: 1500
								});
							}
						},
						fail: (error) => {
							this.$log.error(tag, "获取商品列表失败:", JSON.stringify(error));
							this.loading = false;
							this.loaded = false;
							uni.showToast({
								icon: 'none',
								title: error.errMsg || '网络请求失败',
								duration: 1500
							});
						}
					});
				} catch (e) {
					this.$log.error(tag, "获取商品列表异常:", e.message);
					this.loading = false;
					this.loaded = false;
					uni.showToast({
						icon: 'none',
						title: e.message || '获取商品列表异常',
						duration: 1500
					});
				}
			},

			parseProductList(jsonObject) {
				let productList = [];
				try {
					if (jsonObject.data && Array.isArray(jsonObject.data)) {
						jsonObject.data.forEach((category) => {
							const categoryName = category.categoryName || '其他';
							
							if (category.productList && Array.isArray(category.productList)) {
								category.productList.forEach((product) => {
									if (product && product.productId && product.name && product.price !==
										undefined && product.stock !== undefined) {
										productList.push(new Product(
											product.productId,
											product.name,
											product.price,
											`${this.$constant.BASE_URL}${product.cover}`,
											product.stock,
											categoryName,
											product.sales || 0,
											product.createTime || '',
											false
										));
									} else {
										this.$log.error(tag, `产品数据不完整: ${JSON.stringify(product)}`);
									}
								});
							} else {
								this.$log.error(tag, "解析商品列表失败: 分类产品列表无效");
							}
						});
					} else {
						this.$log.error(tag, "解析商品列表失败: 无效的数据结构");
					}
				} catch (e) {
					this.$log.error(tag, "解析商品列表失败:", e);
				}
				return productList;
			},

			// 获取广告列表
			fetchAdvList() {
				this.$log.info(tag, "fetchAdvList - 开始获取广告列表");
				try {
					uni.request({
						url: `${this.$constant.BASE_URL}/api/adv/list`,
						method: 'GET',
						header: {
							'content-type': 'application/x-www-form-urlencoded'
						},
						success: (res) => {
							this.$log.info(tag, ' 广告列表请求成功 - 响应数据:', res.data);
							
							if (res && res.data) {
								if (res.data.code === 200) {
									try {
										this.advList = this.parseAdvList(res.data);
										this.$log.info(tag, `成功解析 ${this.advList.length} 条广告`);
									} catch (parseError) {
										this.$log.error(tag, "解析广告列表异常:", parseError);
										this.advList = [];
									}
								} else {
									this.$log.error(tag, `获取广告列表返回错误 - code: ${res.data.code}, msg: ${res.data.msg}`);
									this.advList = [];
								}
							} else {
								this.$log.error(tag, "获取广告列表返回无效数据");
								this.advList = [];
							}
						},
						fail: (error) => {
							this.$log.error(tag, `获取广告列表失败: ${JSON.stringify(error)}`);
							this.advList = [];
						}
					});
				} catch (e) {
					this.$log.error(tag, `获取广告列表异常: ${e.message}`);
					this.advList = [];
				}
			},
			
			// 解析广告列表数据
			parseAdvList(jsonObject) {
				let advList = [];
				try {
					if (jsonObject.data && Array.isArray(jsonObject.data)) {
						jsonObject.data.forEach((adv) => {
							if (adv && adv.id) {
								advList.push({
									id: adv.id,
									title: adv.title || '',
									imageUrl: adv.image ? `${this.$constant.BASE_URL}${adv.image}` : this.default_path,
									link: adv.link || '',
									sort: adv.sort || 0
								});
							}
						});
						// 按 sort 排序
						advList.sort((a, b) => a.sort - b.sort);
					}
				} catch (e) {
					this.$log.error(tag, "解析广告列表失败:", e);
				}
				return advList;
			},
			
			// 广告图片加载失败
			onAdvImageError(adv) {
				this.$log.info(tag, `广告图片加载失败: ${adv.title}`);
				adv.imageUrl = this.default_path;
			},
			
			// 点击广告
			onAdvClick(adv) {
				this.$log.info(tag, `点击广告: ${adv.title}`);
				if (adv.link) {
					// 广告链接跳转
					this.$log.info(tag, `广告链接: ${adv.link}`);
				}
			},
		}
	}
</script>

<style>
@import "../../components/style/product.css";
</style>

